/**
 * Created by Alexander on 02.02.2015.
 */

$(document).ready(function () {
    var xml;
    if ((get_cookie("username") !=null)) {
        $.get('users.xml', null, function (data, textStatus) {
            xml = data;
            login = false
            $(xml).find('record').each(function () {
                var item = $(this);
                if (item.find('username').text() == get_cookie("username")) {
                    window.location.replace('newtest.html');
                }
            });
        });
    } else {
        $('#login').click(function () {
            $.get('users.xml', null, function (data, textStatus) {
                xml = data;
                login = false;
                $(xml).find('record').each(function () {
                    var item = $(this);
                    if (item.find('username').text() == $('#usrid').val() && item.find('password').text() == $('#pwd').val()) {
                        login = true;
                        expires = new Date();
                        expires.setTime(expires.getTime() + (1000 * 60 * 10));
                        set_cookie("username", $('#usrid').val(), expires);
                        set_cookie("score", 0, expires);
                        window.open('newtest.html');
                    }
                });
                if (login == false) {
                    alert("incorrect username or password");
                }


            });

        });
    }
});

function set_cookie(name, value, expires) {
    if (!expires) {
        expires = new Date();
    }
    document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; domain=;localhost; path=/";
}


function get_cookie(name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    return(setStr);
}
